<?php
/**
 * File to handle all API requests
 * Accepts GET and POST
 *
 * Each request will be identified by TAG
 * Response will be JSON data
 
  /**
 * check for POST request
 */
mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
if (isset($_POST['tag'])) {
    // get tag
    $tag = $_POST['tag'];
 
    // include db handler
    //require_once 'include/DB_Functions.php';
    //$db = new DB_Functions();
 
    // response Array
    $response = array("tag" => $tag, "success" => 0, "error" => 0);
 
    // check for tag type
    if ($tag == 'register') {
	// To be implemented
        // Request type is Register new route
        $uid = $_POST['uid'];
        $src_lat = $_POST['s_lat'];
        $src_lon = $_POST['s_lon'];
	$src_name= $_POST['s_name'];
	$des_lat = $_POST['d_lat'];
        $des_lon = $_POST['d_lon'];
	$des_name= $_POST['d_name'];
	$via_lat = $_POST['v_lat'];
        $via_lon = $_POST['v_lon'];
	$via_name= $_POST['v_name'];
 
        // check if route already exists
	$result = mysql_query("SELECT * from user_node WHERE user_id = '$uid'");
        $no_of_rows = mysql_num_rows($result);
        if ($no_of_rows > 0) {
            // user is already existed - error response
            $response["error"] = 2;
            $response["error_msg"] = "Route already existed";
            echo json_encode($response);
        } else {
            // store user
	$query1= "INSERT INTO node(src_lat, src_lon, dest_lat, dest_lon, src_name, dest_name, via_lat, via_lon, via_name) VALUES('$src_lat', '$src_lon', '$des_lat', '$des_lon', '$src_name', '$des_name', '$via_lat', '$via_lon','$via_name')";
	$result = mysql_query($query1) or die(mysql_error());
	
	if ($result) {
            // get user details
            $nid = mysql_insert_id(); // last inserted id
	    $res= mysql_query("INSERT INTO user_node(user_id,node_id) VALUES('$uid','$nid')") or die(mysql_error());
		
            $result = mysql_query("SELECT * FROM node WHERE node_id = $nid");
            // return user details
            $route = mysql_fetch_array($result);
        } else {
            $route=false;
        }
	

            if ($route != false) {
                // user stored successfully
                $response["success"] = 1;
                $response["uid"] = $route["node_id"];
                $response["route"]["src_name"] = $route["src_name"];
                $response["route"]["des_name"] = $route["dest_name"];
                $response["route"]["via_name"] = $route["via_name"];
                echo json_encode($response);
            } else {
                // user failed to store
                $response["error"] = 1;
                $response["error_msg"] = "Error occured in Registration";
                echo json_encode($response);
            }
        }
    } else {
        echo "Invalid Request";
    }
} else {
    echo "Access Denied";
}
?>
